<?php

namespace App\Trip\Tencent\Cloud\SDK\COS;

use Illuminate\Support\Str;
use Qcloud\Cos\Client;

class Cos
{

    private string $bucket;
    private string $secret_id;
    private string $secret_key;
    private Client $client;

    public function __construct()
    {
        $this->bucket     = config('qcloud.cos.bucket');
        $this->secret_id  = config('qcloud.cos.secret_id');
        $this->secret_key = config('qcloud.cos.secret_key');

        $this->client = new Client([
            'region'      => 'ap-beijing',
            'credentials' => [
                'secretId'  => $this->secret_id,
                'secretKey' => $this->secret_key,
            ],
        ]);
    }

    public function uploadRemoteImage(string $content, string $path_name): string
    {
        $this->uploadContent($path_name, $content, [
            'ContentType'  => 'image/png',
            'CacheControl' => 'max-age=864000',
        ]);
        return $this->getUrl($path_name);
    }


    /**
     *  上传内存中的 字符串
     * @param string $path_name
     * @param string $content 字符串内容
     * @param array  $options 额外参数
     * @return object
     */
    public function uploadContent(string $path_name, string $content, array $options = []): object
    {
        $data = [
            'Bucket' => $this->bucket,
            'Key'    => $path_name,
            'Body'   => $content,
            'ACL'    => 'public-read',
        ];
        if (!empty($options)) {
            $data = array_merge($options, $data);
        }
        return $this->client->putObject($data);

    }

    /**+
     * 获取对象 地址
     * @param string $path_name
     * @param array  $options
     * @return string
     */
    public function getUrl(string $path_name, array $options = []): string
    {
        $url  = $this->client->getObjectUrl($this->bucket, $path_name, '+10 minutes');
        $base = explode('?', $url);
        return Str::replaceFirst('http:', 'https:', $base[0] ?? '');
    }
}